import React, { ChangeEvent, FC, memo, useEffect, useState } from "react"
import { Input } from "antd"
import { useLocation, useNavigate, useSearchParams } from "react-router-dom"
import { LIST_SEARCH_PARAM_KEY } from "../constant"

const ListSearch: FC = memo(() => {
    const { Search } = Input
    const nav = useNavigate()

    // 获取当前页面的路由
    const { pathname } = useLocation()
    const [value, setValue] = useState("")

    // 获取url携带的参数，并设置到input value中
    const [searchParams] = useSearchParams() // 标准的hook
    useEffect(() => {
        const newVal = searchParams.get(LIST_SEARCH_PARAM_KEY) || ""
        setValue(newVal)
    }, [searchParams])

    // 设置为受控组件
    function handleChange(event: ChangeEvent<HTMLInputElement>) {
        setValue(event.target.value)
    }

    function handleSearch(value: string) {
        // 跳转页面
        nav({
            pathname,
            search: `${LIST_SEARCH_PARAM_KEY}=${value}`
        })
    }

    return (
        <Search
            placeholder="请输入关键词"
            value={value}
            style={{ width: "260px" }}
            enterButton
            size="large"
            allowClear
            onChange={handleChange}
            onSearch={handleSearch}
        />
    )
})

ListSearch.displayName = "ListSearch"
export default ListSearch
